package com.dhj.hospital.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dhj.hospital.mapper.HospitalSetMapper;
import com.dhj.hospital.mapper.HospOrderMapper;
import com.dhj.hospital.mapper.ScheduleMapper;
import com.dhj.hospital.model.OrderInfo;
import com.dhj.hospital.model.Patient;
import com.dhj.hospital.model.Schedule;
import com.dhj.hospital.service.HospitalService;
import com.dhj.hospital.util.ResultCodeEnum;
import com.dhj.hospital.util.YyghException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;

@Service
@Slf4j
public class HospitalServiceImpl implements HospitalService {

    @Autowired
    private ScheduleMapper scheduleMapper;

    @Autowired
    private HospOrderMapper hospOrderMapper;

    @Autowired
    HospitalSetMapper hospitalSetMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> submitOrder(Map<String, Object> paramMap) {
        log.info(JSONObject.toJSONString(paramMap));

        /*
         医院获取平台数据，同时封装医院自己的数据给平台
         */
        String hoscode = (String) paramMap.get("hoscode");
        String depcode = (String) paramMap.get("depcode");
        String hosScheduleId = System.currentTimeMillis() + "";// 医院自己的排班 id
        String reserveDate = (String) paramMap.get("reserveDate");
        String reserveTime = (String) paramMap.get("reserveTime");// 上午 / 下午
        String amount = (String) paramMap.get("amount");

        Map<String, Object> resultMap = new HashMap<>();

        // 记录预约记录
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setPatientId(1L);
        orderInfo.setScheduleId(Long.parseLong(hosScheduleId));
        Integer number = Integer.parseInt(RandomStringUtils.randomNumeric(6));// 医院自己的预约号序
        orderInfo.setNumber(number);
        orderInfo.setAmount(new BigDecimal(amount));// 医事服务费
        String fetchTime = "0".equals(reserveDate) ? " 09:30前" : " 14:00前";
        orderInfo.setFetchTime(reserveTime + fetchTime);
        orderInfo.setFetchAddress("一楼 9 号窗口");

        // 默认: 未支付
        orderInfo.setOrderStatus(0);

        // 医院平台保存订单信息
        hospOrderMapper.insert(orderInfo);

        resultMap.put("resultCode", "0000");
        resultMap.put("resultMsg", "预约成功");

        // 预约记录唯一标识（医院预约记录主键）
        resultMap.put("hosRecordId", orderInfo.getId());

        // 预约号序
        resultMap.put("number", number);

        // 取号时间
        resultMap.put("fetchTime", reserveDate + " 09:00前");

        // 取号地址
        resultMap.put("fetchAddress", "一层 114 窗口");

        return resultMap;
    }

    // 更新订单付款状态信息
    @Override
    public void updatePayStatus(Map<String, Object> paramMap) {

        // 根据预约号序查询订单信息
        String number = (String) paramMap.get("number");
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("number", number);
        OrderInfo orderInfo = hospOrderMapper.selectOne(wrapper);

        if (null == orderInfo) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        // 更新支付状态
        orderInfo.setOrderStatus(1);// 已支付
        orderInfo.setPayTime(new Date());
        hospOrderMapper.updateById(orderInfo);
    }

    // 更新退款状态
    @Override
    public void updateCancelStatus(Map<String, Object> paramMap) {
        // 根据预约号序查询订单记录
        String number = (String) paramMap.get("number");

        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();

        wrapper.eq("number", number);

        OrderInfo orderInfo = hospOrderMapper.selectOne(wrapper);

        if (null == orderInfo) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        // 取消预约
        orderInfo.setOrderStatus(-1);
        orderInfo.setQuitTime(new Date());
        hospOrderMapper.updateById(orderInfo);
    }

    private Schedule getSchedule(String frontSchId) {
        return scheduleMapper.selectById(frontSchId);
    }

    /**
     * 医院处理就诊人信息
     *
     * @param patient
     */
    private Long savePatient(Patient patient) {
        // 业务: 略
        return 1L;
    }

    @Override
    public boolean isSignKey(String sisgnKey) {
        if (StringUtils.isEmpty(sisgnKey)) {
            throw new YyghException("签名为空!", 204);
        }

        return sisgnKey.equals(hospitalSetMapper.selectById(1).getSignKey());
    }
}
